import { nextTick, ref } from "vue"

export const useShowRoadCondition = (docName, map) => {
  //定义服务
  let service = {
    name: docName,
    layerId: 1,
  }
  console.log(docName)
  //实时路况
  // （500-1000为绿色；1000-1500为黄色；1500-2000位红色）
  let queryList = [
    {
      where: "车流量>=500 and 车流量<1000",
      color: "green",
    },
    {
      where: "车流量>=1000 and 车流量<1500",
      color: "yellow",
    },
    {
      where: "车流量>=1500 and 车流量<=2000",
      color: "red",
    },
  ]
  // 定义一个变量控制路况信息的显隐
  const flag = ref(false)
  //定义响应式source
  let roadSource = ref(null)
  //定义响应式layer
  let roadLayer = ref(null)
  //存放layers,便于后面删除
  let roadlayers = ref([])
  const showRoadCondition = () => {
    flag.value = !flag.value
    if (flag.value) {
      //遍历查询路段
      queryList.forEach((item) => {
        Query.queryByAttr({
          where: item.where,
          service,
          callback: (res) => addRoad(res, item.color),
        })
      })
      //查询路段成功的回调
      function addRoad(res, color) {
        //反序列化
        // 将其转为ol要素
        var format = new Zondy.Format.PolygonJSON()
        //将MapGIS要素JSON反序列化为ol.Feature类型数组
        var features = format.read(res)
        // 将查询到的要素添加到高亮图层中
        //定义source
        roadSource.value = new ol.source.Vector({
          wrapX: false,
        })
        roadSource.value.addFeatures(features)
        //定义图层
        roadLayer.value = new ol.layer.Vector({
          source: roadSource.value,
          style: new ol.style.Style({
            //填充色
            fill: new ol.style.Fill({
              color: color,
            }),
            //边线颜色
            stroke: new ol.style.Stroke({
              color: color,
              width: 5,
            }),
          }),
        })
        roadlayers.value.push(roadLayer.value)
        map.value.addLayer(roadLayer.value)
      }
    } else {
      roadlayers.value.forEach((item) => {
        map.value.removeLayer(item)
      })
      roadSource.value.clear()
    }
  }
  return { showRoadCondition,flag }
}
